package com.dayaokeji.rhythmschoolstudent.client.main;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.StudentIdLoginActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.SignUtils;
import com.dayaokeji.rhythmschoolstudent.utils.TimeUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Permission;

import io.reactivex.functions.Consumer;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import retrofit2.Call;

/**
 * 启动页
 */
public class SplashActivity extends BaseActivity {

    private static final long DEFAULT_DELAYED = 1000L;

    private Handler mainHandler;

    private static final SystemApi systemApi = ApiUtils.getApi(SystemApi.class);
    private Call<ServerResponse<String>> refreshTokenCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mainHandler = AndroidUtils.getMainHandler();
        mainHandler.postDelayed(startLoginRunnable, DEFAULT_DELAYED);
        PermissionUtil.getPermissionName(this, new String[]{Permission.READ_PHONE_STATE});
        SignUtils.asyncNetTime();
        TimeUtils.asyncNetDate();
    }


    private Runnable startLoginRunnable = () -> setBaseUrl();

    private void setBaseUrl() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            PackageManager pm = getPackageManager();
            boolean permission_readStorage = (PackageManager.PERMISSION_GRANTED ==
                    pm.checkPermission("android.permission.READ_PHONE_STATE", getPackageName()));

            if (userInfo.getOpenadsStatus() != null && userInfo.getOpenadsStatus().equals("1") && permission_readStorage) {

                Intent intent = new Intent(this, OpenAdverActivity.class);
                startActivity(intent);
                ActivityStackManager.finish();
            } else {

                if (currentRemoteHost != null) {
                    String host = currentRemoteHost.getHost();
                    if (!TextUtils.isEmpty(host)) {
                        RetrofitUrlManager.getInstance().setGlobalDomain(host);
                        if (UserUtils.isExpiresLogin()) {
                            refresh();
                        } else {
                            startMain();
                        }
                    } else {
                        UserUtils.setAccessToken("");
                        UserUtils.setUserInfo(null);
                        UserInfoDao.delUserInfo();
                        Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                } else {
                    UserUtils.setAccessToken("");
                    UserUtils.setUserInfo(null);
                    UserInfoDao.delUserInfo();
                    Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        } else {

            if (currentRemoteHost != null) {
                String host = currentRemoteHost.getHost();
                if (!TextUtils.isEmpty(host)) {
                    RetrofitUrlManager.getInstance().setGlobalDomain(host);
                    if (UserUtils.isExpiresLogin()) {
                        refresh();
                    } else {
                        startMain();
                    }
                } else {
                    UserUtils.setAccessToken("");
                    UserUtils.setUserInfo(null);
                    UserInfoDao.delUserInfo();
                    Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            } else {
                UserUtils.setAccessToken("");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        }


    }

    private void startMain() {
        if (UserUtils.checkLogin(this)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            ActivityStackManager.finish();
        }
    }


    @Override
    protected void onDestroy() {
        if (mainHandler != null) {
            mainHandler.removeCallbacks(startLoginRunnable);
        }
        mainHandler = null;
        if (refreshTokenCall != null) {
            refreshTokenCall.cancel();
        }

        super.onDestroy();
    }

    private void refresh() {
        final UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            final String token = userInfo.getToken();
            if (!TextUtils.isEmpty(token)) {
                refreshToken();
            } else {
                UserUtils.setAccessToken("");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        } else {
            UserUtils.setAccessToken("");
            UserUtils.setUserInfo(null);
            UserInfoDao.delUserInfo();
            Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 刷新Token
     */
    private void refreshToken() {
        refreshTokenCall = systemApi.refreshToken();
        refreshTokenCall.enqueue(new ServerCallback<String>() {
            @Override
            public void onResponse(boolean success, ServerResponse<String> response) {
                if (success) {
                    Logger.d("new token = " + response.getBody());
                    PrefUtils.setExpiresLoginTime(System.currentTimeMillis());
                    UserUtils.setAccessToken(response.getBody());
                    startMain();
                } else {
                    ToastUtils.info("自动登录失败，请重新登录");
                    UserUtils.setUserInfo(null);
                    UserInfoDao.delUserInfo();
                    Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<String>> call, Throwable t) {
                super.onFailure(call, t);
                ToastUtils.info("自动登录失败，请重新登录");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(SplashActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
